package com.inspectortime.service;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

public class SaxCodeElementHandler extends DefaultHandler {

	private Map<String, String> currentElementNameValueMap;
	private List<Map<String, String>> elementNameValueMaps;
	private String currentElementName;
	private boolean jobDone = false;

	public void startElement(String namespaceUri, String localName,
			String qualifiedName, Attributes attributes) throws SAXException {
		if (qualifiedName.equals("geonames")) {
			jobDone = false;
			elementNameValueMaps = new ArrayList<Map<String, String>>();
		} else if (qualifiedName.equals("code")) {
			currentElementNameValueMap = new HashMap<String, String>();
		} else {
			currentElementName = qualifiedName;
		}
	}

	public void endElement(String namespaceUri, String localName,
			String qualifiedName) throws SAXException {
		if (qualifiedName.equals("code")) {
			elementNameValueMaps.add(currentElementNameValueMap);
		}
	}

	public void endDocument() throws SAXException {
		jobDone = true;
	}

	public List<Map<String, String>> getElementNameValueMaps() {
		return elementNameValueMaps;
	}

	public Map<String, String> getFirstElementNameValue() {
		if (!elementNameValueMaps.isEmpty()) {
			return elementNameValueMaps.iterator().next();	
		}
		return Collections.EMPTY_MAP;
	}

	public void characters(char[] chars, int startIndex, int endIndex) {
		if (currentElementNameValueMap != null && currentElementName != null) {
			String dataString = new String(chars, startIndex, endIndex).trim();
			currentElementNameValueMap.put(currentElementName, dataString);
			currentElementName = null;
		}
	}

}
